#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main(int argc, char const *argv[])
{
    if( argc != 2)
    {
        printf("Pls input: ./a.out <dst file name>\n");
        return -1;
    }

    int fdDst = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0664);
    if ( -1 == fdDst)
    {
        perror("Fail to open");
        return -1;
    }
    printf("The file descriptor of file <%s> is %d\n", argv[1], fdDst);

    off_t otSeekRet;
    otSeekRet = lseek(fdDst, 10, SEEK_SET);
    if( -1 == otSeekRet)
    {
        perror("Fail lseek");
        return -1;
    }
    printf("#1 lseek return value is %ld\n", otSeekRet);  //10
    
    ssize_t szWriteRet;
    szWriteRet = write(fdDst, "A", 1);
    if ( -1 == szWriteRet )
    {
        perror("fail write");
        return -1;
    }
    otSeekRet = lseek(fdDst, 0, SEEK_CUR);
    printf("#2 lseek return value is %ld\n", otSeekRet);  //11

    otSeekRet = lseek(fdDst, -5, SEEK_CUR);
    write(fdDst, "B", 1);
    printf("#3 lseek return value is %ld\n", otSeekRet);  //6

    otSeekRet = lseek(fdDst, 3, SEEK_END);
    write(fdDst, "C", 1);
    printf("#4 lseek return value is %ld\n", otSeekRet);  //14

    otSeekRet = lseek(fdDst, 0, SEEK_SET);
    printf("#5 lseek return value is %ld\n", otSeekRet);  //0

    otSeekRet = lseek(fdDst, 0, SEEK_END);
    printf("Total length of file <%s> is %ld\n", argv[1], otSeekRet);  //15


    otSeekRet = lseek(fdDst, -2, SEEK_SET);
    printf("Return value of lseek with negtive offset based on SEEK_SET is %ld with strerror<%s>\n", 
            otSeekRet, strerror(errno) );
    // -1, Invalid argument

    close(fdDst);

    return 0;
}

/*

lseek RETURN VALUE
       Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of  the  file.   On  error,  the
       value (off_t).
       -1 is returned and errno is set to indicate the error.


*/
